'use strict';

const Controller = require('egg').Controller;

class FontController extends Controller {
    async desc() {
    this.ctx.body = 'this is a controller of gen font';
  }

  async gen_font() {
    const ctx = this.ctx;
    const createRule = {
      school_id: {type: 'int'},
      content: {type: 'string'}
    }

    // 校验参数
    // ctx.validate(createRule);
    const body = ctx.request.body;
    var school_id = body.school_id;
    // in service
    // const req = Object.assign(body.content, body.school_id);
  
    // console.log("request body: " + body);
    console.log("request school_id: " + body.school_id);
    // gen font
    if(! school_id){
      res = 'error: school_id is not specify';
      this.ctx.body = res;
      return false;
    }
    // const dirname = '/Users/yang/Downloads/html/' + school_id;
    const dirname = 'F:\\test_html\\temp\\html' + school_id;
    var res;
    res = await this.gen_font_by_spider(dirname);
    console.log('request finish return res: ' + res);


     // 设置响应内容和响应状态码
     // ctx.status = 201;
     //gen font by font-spider
    this.ctx.body = res;
  }

  // async sleep(delay){
  //   return function(){
  //     return new Promise(function(resolve, reject){
  //       setTimeout(resolve, delay);
  //     });
  //   };
  // }

  /**
   *  gen font by font-spider
   */
  async gen_font_by_spider(dirname){
    var is_finish = false;
    var fontSpider = require('font-spider');
    var res='error';
    var filepath = dirname + '\\001.html';
    var filepaths = [];
    const upload_to_qiniu_fun = this.upload_to_qiniu;
    // console.log('upload_to_qiniu_fun: ' + upload_to_qiniu_fun);
    filepaths.push(filepath);
    fontSpider.spider(filepaths, {
      silent: false
    }).then(function(webFonts) {
      fontSpider.compressor(webFonts, {backup: true}, function(){
        // console.log('upload_to_qiniu_fun: ' + upload_to_qiniu_fun);
        is_finish = true;
        res = 'ok';
        console.log('finish compressor webFonts res is: ' + res);
        console.log('webFonts: ' + webFonts);
        //start upload
        var font_types = ['eot', 'svg', 'ttf', 'woff'];
        for(var i=0; i<font_types.length; i++){
          var font_file_path = dirname + "\\font\\xindi."+font_types[i];
          upload_to_qiniu_fun(font_file_path);
        }

      });
      res = 'start';
      console.log('start compressor webFonts');
    }).then(function(webFonts) {
    }).catch(function(errors) {
      is_finish = true;
      console.error('errors: ' + errors);
      res = errors;
    });

  //   fontSpider.spider(filepaths, {
  //     silent: false
  //   }).then(function(webFonts, upload_to_qiniu_fun) {
  //     fontSpider.compressor(webFonts, {backup: true}, function(upload_to_qiniu_fun){
  //       console.log('我是回调');
  //       res = 'ok';
  //       console.log('finish compressor webFonts res is: ' + res);
  //       console.log('webFonts: ' + webFonts);
  //       //start upload
  //       var font_types = ['eot', 'svg', 'ttf', 'woff'];
  //       for(var i=0; i<font_types.length; i++){
  //         var font_file_path = dirname + "/font/test."+font_types[i];
  //         upload_to_qiniu_fun(font_file_path);
  //       }
  //     });
  //     res = 'start';
  //     console.log('start compressor webFonts');
  //   }).then(function(webFonts) {
  //     
  //   }).catch(function(errors) {
  //     console.error('errors: ' + errors);
  //     res = errors;
  //   });
  //
  //
    console.log('sleep start');

    while(!is_finish){
      await this.sleep(100);
    }
    console.log('sleep end');
    console.log('return res: ' + res);
    return res;
  }


  async sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));

  }

  async demo() {
    console.log('Taking a break...');
    await sleep(2000);
    console.log('Two second later');

  }

  //上传到七牛
   upload_to_qiniu(filepath){

    console.log('start upload ----> ' + filepath);
    var path = require('path');
    var qiniu = require('qiniu');
    var accessKey = 'fOhL3drkHp3SpBAHhB5dBCKtKv1Zh8Hc_TbaqLxF';
    var secretKey = 'otKO29XAnTbSRt3Fzxp7g23CLWO9ezMBypyqDoZD';
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    var bucket = 'rongtong-test'
    var options = {
      scope: bucket + ":" + filepath,
      expires: 7200,
      force: true
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken=putPolicy.uploadToken(mac);

    var config = new qiniu.conf.Config();

    // var localFile = '/Users/yang/git/egg-example/README.md';
    // var file_key = path.basename(filepath);
    var file_key = filepath;
    console.log('file_key: ' + file_key);

    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();
  
    var res='null';
    formUploader.putFile(uploadToken, file_key, filepath, putExtra, function(respErr,
          respBody, respInfo) {
      console.log('finish upload ----> ' + filepath);
      if (respErr) {
        console.log('file_key: ' + file_key + ' ---------> respErr' + respErr);
        throw respErr;

      }
      if (respInfo.statusCode == 200) {
        console.log('file_key: ' + file_key + ' -------> respBody200' + respBody);

      } else {
        console.log(respInfo.statusCode);
        console.log('file_key: ' + file_key +  '--------> respInfo: ' + respInfo);

      }
      res = respBody;
    });
  }

  async get_file_name(filepath){
    var path = require('path');
    return path.basename(filepath);
  }


}


module.exports = FontController;
